package ynu.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import ynu.dao.IUserListDao;
import ynu.po.LoginDTO;
import ynu.po.UserList;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController//接口方法返回对象 转换为json文本
@RequestMapping(value = "/user")
@Tag(name="用户信息相关服务")
@CrossOrigin(origins = "*",
        allowedHeaders = "*",methods = {
        RequestMethod.DELETE,RequestMethod.GET,RequestMethod.PUT,RequestMethod.POST
})
public class UserListController {
    @Resource
    private IUserListDao lDao;

    @Operation(summary = "用户信息录入")
    @Parameter(name = "user", description = "人员信息Json格式")
    @PostMapping(value = "/saveUser")
    public ResponseEntity<UserList> saveUser(@RequestBody UserList userList) {
        UserList userList1 = lDao.save(userList);
        return new ResponseEntity<>(userList1, HttpStatus.CREATED);
    }

    @Operation(summary = "用户信息查询")
    @Parameters({
            @Parameter(name = "condition", description = "查询条件")
    })
    @GetMapping(value = "/getUser")
    public ResponseEntity<List<UserList>> getUsers(@RequestParam(required = false) String condition) {
        List<UserList> allUsers = lDao.findAll();
        if (StringUtils.hasText(condition)) {
            List<UserList> filteredUsers = new ArrayList<>();
            String[] conditions = condition.split(" AND ");
            for (UserList user : allUsers) {
                boolean match = true;
                for (String singleCondition : conditions) {
                    String[] parts = singleCondition.split(":");
                    if (parts.length == 2) {
                        String field = parts[0].trim();
                        String value = parts[1].trim();
                        switch (field) {
                            case "id":
                                if (!user.getUserId().toString().equals(value)) {
                                    match = false;
                                    break;
                                }
                                break;
                            case "name":
                                if (!user.getUserName().equals(value)) {
                                    match = false;
                                    break;
                                }
                                break;
                            case "password":
                                if (!user.getPassword().equals(value)) {
                                    match = false;
                                    break;
                                }
                                break;
                            case "email":
                                if (!user.getEmail().equals(value)) {
                                    match = false;
                                    break;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    if (!match) {
                        break;
                    }
                }
                if (match) {
                    filteredUsers.add(user);
                }
            }
            return new ResponseEntity<>(filteredUsers, HttpStatus.OK);
        }
        return new ResponseEntity<>(allUsers, HttpStatus.OK);
    }



    @Operation(summary = "删除用户信息")
    @Parameter(name = "userId", description = "用户id")
    @DeleteMapping(value = "/deleteUser//{userId}")
    public ResponseEntity<Void> deleteUser(@PathVariable("userId") Long userId) {
        lDao.deleteById(userId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Operation(summary = "用户注册")
    @Parameter(name = "user", description = "用户信息JSON格式")
    @PostMapping(value = "/register")
    public UserList insert(@RequestBody UserList stu) {
        return lDao.save(stu);
    }


    // 用户登录接口
    @Operation(summary = "用户登录服务")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
            @Parameter(name = "password", description = "密码")
    })
    @PostMapping(value = "/login")
    public ResponseEntity<UserList> login(@RequestBody LoginDTO loginDTO) {
        UserList user = lDao.findUserListByUserName(loginDTO.getUsername());
        if (user != null && user.getPassword().equals(loginDTO.getPassword())) {
            return new ResponseEntity<>(user, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
    }

    @Operation(summary = "用户信息更新")
    @PutMapping("/update")
    public ResponseEntity<UserList> updateUser(@RequestParam Long id,
                                               @RequestParam String userName,
                                               @RequestParam String career,
                                               @RequestParam String email,
                                               @RequestParam Long phonenum,
                                               @RequestParam Boolean sex) {
        Optional<UserList> optionalUserList = lDao.findById(id);
        if (optionalUserList.isPresent()) {
            UserList userList = optionalUserList.get();
            userList.setUserName(userName);
            userList.setCareer(career);
            userList.setEmail(email);
            userList.setPhonenum(phonenum);
            userList.setSex(sex);
            UserList updatedUser = lDao.save(userList);
            return ResponseEntity.ok(updatedUser);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @Operation(summary = "检查邮箱是否唯一")
    @GetMapping("/checkEmailUnique")
    public ResponseEntity<Boolean>checkEmail(@RequestParam String email){
        boolean exists= lDao.existsByEmail(email);
        return new ResponseEntity<>(exists,HttpStatus.OK);
    }
}
